﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using OTA.Notification.BO.Dictionary;
using OTA.Notification.Entity.Dictionary;
using Strive.DataAccess.Base.Model.SearcherObject;
using Strive.DataAccess.Base.Model.PageObject;
using System.Xml;
using System.Collections.Generic;

namespace OTA.Notification.Web.Dictionary
{
    public partial class directory : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ////////////////////////////////////////////////////
                //jay.gu添加
                //用于AJAX获取类型列表
                if (!string.IsNullOrEmpty(Request.QueryString["action"]))
                {
                    if (Request.QueryString["action"].Equals("dic"))
                    {
                        //get json

                        string strJSON = getJson();


                        Response.Write(strJSON);
                        Response.End();

                        return;
                    }
                }
                //////////////////////////////////////////////////

                int id = 0;
                try
                {
                    id = Convert.ToInt32(Request.QueryString["id"]);
                }
                catch { }
                string pcode = Request.QueryString["code"];
                txtpcode.Text = pcode.Split('|')[pcode.Split('|').Length-1];

                ddltype.DataSource = new DictionaryBO().getAllDictionary("", "", OTA.Notification.Common.LanguageType.English);
                ddltype.DataValueField = "code";
                ddltype.DataTextField = "name";
                ddltype.DataBind();

                #region
                if (pcode != "")
                {
                    int i = 0;
                    string urlstr = "";
                    string[] urls = pcode.Split('|');
                    foreach (string curl in urls)
                    {
                        if (curl != "")
                        {
                            string purl = "";
                            for (int stepi = 0; stepi <= i; stepi++)
                            {
                                if (urls[stepi] != "")
                                    purl += "|" + urls[stepi];
                            }
                            purl = System.Web.HttpUtility.UrlEncode(purl);
                            if (i < urls.Length - 1)
                                urlstr += " -> <!--a href=\"list.aspx?code=" + purl + "\"-->" + curl + "<!--/a-->";
                            else
                                urlstr += " -> " + curl;
                        }
                        i++;
                    }
                    Literal2.Text = urlstr;
                }
                #endregion

                if (id > 0)
                {
                    OTA_DICTIONARY _dict = new DictionaryBO().getDictionary(id);

                    if (_dict != null)
                    {
                        txtpcode.ReadOnly = false;
                        hidid.Value = id.ToString();
                        btnsave.Text = "修改";
                        btndel.Visible = true;
                        initdata(_dict);
                    }
                    else
                    {
                        btnsave.Text = "新增";
                    }
                }
                else
                {
                    btnsave.Text = "新增";
                }
            }
        }


        private string getJson()
        {
            string strJSON = "{ \"data\":[";

            IList<OTA_DICTIONARY> lstOTA = new DictionaryBO().getAllDictionary("", "", OTA.Notification.Common.LanguageType.English);

            foreach (OTA_DICTIONARY dic in lstOTA)
            {
                strJSON += "{\"name\":\"" + HttpUtility.HtmlEncode(dic.NAME) + "\"," + "\"code\":\"" + HttpUtility.HtmlEncode(dic.CODE) + "\"},";
 
            }

            strJSON = strJSON.TrimEnd(',');
            strJSON += "]}";

            return strJSON;
        }

        private void initdata(OTA_DICTIONARY _dict)
        {
            txtcode.Text = _dict.CODE;
            txtpcode.Text = _dict.PARENT_CODE;
            txtvalue.Text = _dict.VALUE.ToString();
            ddltype.SelectedValue = _dict.TYPE;
            bindxml(_dict.NAME);

        }

        #region
        private void bindxml(string p)
        {
            XmlDocument _doc = new XmlDocument();
            _doc.LoadXml(p);

            foreach (XmlNode _node in _doc.ChildNodes[0].ChildNodes)
            {
                switch (_node.Attributes["Language"].Value)
                {
                    case "zh-cn":
                        txtcn.Text = _node.Attributes["Name"].Value;
                        break;
                    case "en-us":
                        txten.Text = _node.Attributes["Name"].Value;
                        break;
                }
            }
        }

        private string readxml()
        {
            XmlDocument _doc = new XmlDocument();
            _doc.LoadXml("<CodeContents></CodeContents>");

            //中文
            if (txtcn.Text != "")
            {
                XmlNode _node = _doc.CreateNode("element", "CodeContent", "");
                XmlAttribute _atrL = _doc.CreateAttribute("Language");
                XmlAttribute _atrN = _doc.CreateAttribute("Name");
                _atrL.Value = "zh-cn";
                _atrN.Value = txtcn.Text;
                _node.Attributes.Append(_atrN);
                _node.Attributes.Append(_atrL);

                XmlElement elment = _doc.DocumentElement;
                elment.AppendChild(_node);
            }
            //英文
            if (txten.Text != "")
            {
                XmlNode _node = _doc.CreateNode("element", "CodeContent", "");
                XmlAttribute _atrL = _doc.CreateAttribute("Language");
                XmlAttribute _atrN = _doc.CreateAttribute("Name");
                _atrL.Value = "en-us";
                _atrN.Value = txten.Text;
                _node.Attributes.Append(_atrN);
                _node.Attributes.Append(_atrL);

                XmlElement elment = _doc.DocumentElement;
                elment.AppendChild(_node);   
            }

            //其他文扩充
            //.................


            return _doc.InnerXml;
        }
        #endregion

        protected void Button1_Click(object sender, EventArgs e)
        {

            //Jay.Gu添加,获取下拉列表选择的值

            string strSelectValue = string.Empty;
            string[] strValues = null;

            if (!string.IsNullOrEmpty(Request.Params["selectTypeValue[]"]))
            {
                strSelectValue = Request.Params["selectTypeValue[]"];

                strValues = strSelectValue.Split(','); //数组内存放下拉列表的CODE值

                
            }


            if (txten.Text == "" && txtcn.Text == "")
            {
                Response.Write("<script language=javascript>alert('必须填写一个 name！');history.go(-1);</script>");
            }
            else
            {
                int id = Convert.ToInt32(hidid.Value);
                OTA_DICTIONARY _dict = new OTA_DICTIONARY();
                if (id > 0)
                    _dict = new DictionaryBO().getDictionary(id);

                _dict.PARENT_CODE = txtpcode.Text.Trim();
                _dict.CODE = txtcode.Text.Trim();
                if (txtvalue.Text != "")
                    _dict.VALUE = Convert.ToInt32(txtvalue.Text);
                _dict.NAME = readxml();
                _dict.TYPE = ddltype.SelectedValue;
                _dict.ID = Convert.ToInt32(hidid.Value);

                if (_dict.CODE != "")//如果不是最终数据，则type为空
                    _dict.TYPE = "";
                
                if (_dict.ID > 0)
                {
                    _dict.LAST_UPDATE_TIME = DateTime.Now; 
                    if (new DictionaryBO().updateDictionary(_dict))
                        //Response.Write("<script language=javascript>alert('修改成功！');</script>");
                        Response.Write("<script language=javascript>window.parent.Close();</script>");
                    else
                        Response.Write("<script language=javascript>alert('修改失败，可能是数据项重复，或请稍候重试！');history.go(-1);</script>");
                }
                else
                {
                    _dict.CREATE_TIME = DateTime.Now;
                    _dict.LAST_UPDATE_TIME = DateTime.Now;
                    if (new DictionaryBO().insertDictionary(_dict))
                        //Response.Write("<script language=javascript>alert('新增成功！');</script>");
                        Response.Write("<script language=javascript>window.parent.Close();</script>");
                    else
                        Response.Write("<script language=javascript>alert('新增失败，可能是数据项重复，或请稍候重试！');history.go(-1);</script>");
                }
            }
        }

        protected void btndel_Click(object sender, EventArgs e)
        {
            if (new DictionaryBO().deleteDictionary(Convert.ToInt32(hidid.Value)))
            {
                //Response.Write("<script language=javascript>alert('删除成功！');</script>");
                Response.Write("<script language=javascript>window.parent.Close();</script>");
                
            }
            else
                Response.Write("<script language=javascript>alert('删除失败，请稍候再试！');history.go(-1);</script>");
        }

        
    }
}
